package com.hzhr.iot.web.util;


import org.apache.commons.lang3.StringUtils;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

public class DateHelper {

    //默认格式
    private static String datePattern = "yyyy-MM-dd";
    private static String datePattern2 = "yyyy-MM";
    private static String timePattern = datePattern + " HH:mm:ss";

    /*
    日期转为字符串
     */
    public static final String date2Str(Date aDate) {
        SimpleDateFormat df = null;
        String returnValue = "";
        if (aDate != null) {
            df = new SimpleDateFormat(timePattern);
            returnValue = df.format(aDate);
        }
        return (returnValue);
    }

    /*
    日期转为字符串
     */
    public static final String date2Str(String pattern, Date aDate) {
        SimpleDateFormat df = null;
        String returnValue = "";
        if (aDate != null) {
            df = new SimpleDateFormat(pattern);
            returnValue = df.format(aDate);
        }
        return (returnValue);
    }

    /*
    字符串转为日期，失败返回null
     */
    public static final Date str2Date(String pattern, String strDate)
            throws ParseException {
        SimpleDateFormat df = null;
        Date date = null;
        df = new SimpleDateFormat(pattern);

        try {
            if (StringHelper.isEmpty(strDate))
                return null;
            date = df.parse(strDate);
        } catch (Exception pe) {

        }
        if(date==null)
            date=DateHelper.str2Date02(timePattern,strDate);
        if (date == null)
            date = DateHelper.str2Date02(datePattern, strDate);
        if (date == null)
            date = DateHelper.str2Date02(datePattern2, strDate);
        if (date == null)
            date = new Date(TConverter.ObjectToLong(strDate));
        return (date);
    }
    public static final Date str2Date02(String pattern, String strDate)
            throws ParseException {
        SimpleDateFormat df = null;
        Date date = null;
        df = new SimpleDateFormat(pattern);

        try {
            if (StringHelper.isEmpty(strDate))
                return null;
            date = df.parse(strDate);
        } catch (Exception pe) {

        }
        return (date);
    }

    /*
    字符串转为日期，失败返回null
     */
    public static final Date str2Date(String strDate)
            throws ParseException {
        SimpleDateFormat df = null;
        Date date = null;
        df = new SimpleDateFormat(timePattern);

        try {
            if (StringUtils.isEmpty(strDate))
                return null;
            date = df.parse(strDate);
        } catch (Exception pe) {

        }
        if (date == null)
            date = DateHelper.str2Date02(datePattern, strDate);
        if (date == null)
            date = DateHelper.str2Date02(datePattern2, strDate);
        if (date == null)
            date = new Date(TConverter.ObjectToLong(strDate));
        return (date);
    }

    //获取当前时间
    public static String getTimeNow() {
        Date nowTime = new Date();
        return date2Str(nowTime);
    }

    //获取当前时间
    public static String getTimeNow(String pattern) {
        Date nowTime = new Date();
        return date2Str(pattern, nowTime);
    }

    //增加日
    public static Date addDays(Date date, int days) {
        Calendar now = Calendar.getInstance();
        now.setTime(date);
        now.set(Calendar.DATE, now.get(Calendar.DATE) + days);
        return now.getTime();
    }


    public static Date addYear(Date date, int year) {
        Calendar now = Calendar.getInstance();
        now.setTime(date);
        now.add(Calendar.YEAR, year);
        return now.getTime();
    }

    //获取当天开始时间
    public static Date getDayStartTime(Date date) {
        Calendar todayStart = Calendar.getInstance();
        todayStart.setTime(date);
        todayStart.set(Calendar.HOUR_OF_DAY, 0);
        todayStart.set(Calendar.MINUTE, 0);
        todayStart.set(Calendar.SECOND, 0);
        todayStart.set(Calendar.MILLISECOND, 0);
        return todayStart.getTime();
    }

    //获取当天结束时间
    public static Date getDayEndTime(Date date) {
        Calendar todayEnd = Calendar.getInstance();
        todayEnd.setTime(date);
        todayEnd.set(Calendar.HOUR_OF_DAY, 23);
        todayEnd.set(Calendar.MINUTE, 59);
        todayEnd.set(Calendar.SECOND, 59);
        todayEnd.set(Calendar.MILLISECOND, 999);
        return todayEnd.getTime();
    }

    /***
     * 获取当前时间的前部分
     * @return
     */
    public static String getStringDateShort(Date currentTime) {
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
        String dateString = formatter.format(currentTime);
        return dateString;
    }

    /***
     * 获取当前时间的后部分
     * @return
     */
    public static String getTimeShort(Date currentTime) {
        SimpleDateFormat formatter = new SimpleDateFormat("HH:mm:ss");
        String dateString = formatter.format(currentTime);
        return dateString;
    }

    //获取时间戳
    public static String getTimestamp(Date date, int expireTime) {
        SimpleDateFormat formatter = new SimpleDateFormat(timePattern);
        Calendar now = Calendar.getInstance();
        now.setTime(date);
        now.add(Calendar.SECOND, expireTime);
        long ts = now.getTime().getTime();
        return String.valueOf(ts);
    }

    public static Date addSecond(Date date, int expireTime) {
        Calendar now = Calendar.getInstance();
        now.setTime(date);
        now.add(Calendar.SECOND, expireTime);
        return now.getTime();
    }

    //增加分
    public static Date addMinute(Date date, int expireTime) {
        Calendar now = Calendar.getInstance();
        now.setTime(date);
        now.add(Calendar.MINUTE, expireTime);
        return now.getTime();
    }
    //增加月
    public static Date addMonth(Date date, int month) {
        Calendar now = Calendar.getInstance();
        now.setTime(date);
        now.add(Calendar.MONTH, month);
        return now.getTime();
    }

    //获取月初
    public static Date getMonthBeginTime(Date date) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.set(Calendar.DAY_OF_MONTH, calendar.getActualMinimum(Calendar.DAY_OF_MONTH));
        calendar.set(Calendar.HOUR_OF_DAY, 0);
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.SECOND, 0);
        return calendar.getTime();
    }

    public static Date getMonthLastTime(Date date){
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.MONTH, 1);
        calendar.set(Calendar.DAY_OF_MONTH, 0);
        calendar.set(Calendar.HOUR_OF_DAY, 23);
        calendar.set(Calendar.MINUTE, 59);
        calendar.set(Calendar.SECOND, 59);
        return calendar.getTime();
    }


    //获取日开始时间
    public static Date getDayBeginTime(Date date) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.set(Calendar.HOUR_OF_DAY, 0);
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.SECOND, 0);
        return calendar.getTime();
    }

    //获取日期的天
    public static int getDay(Date date){
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        return calendar.get(Calendar.DATE);
    }

    /**
     * 根据当前日期获得所在周的日期区间（周一和周日日期）
     *
     * @return
     * @throws ParseException
     */
    public static TimeRange getThisWeekRange(Date date)  {
        Calendar cal = Calendar.getInstance();
        cal.setTime(date);
        // 判断要计算的日期是否是周日，如果是则减一天计算周六的，否则会出问题，计算到下一周去了
        int dayWeek = cal.get(Calendar.DAY_OF_WEEK);// 获得当前日期是一个星期的第几天
        if (1 == dayWeek) {
            cal.add(Calendar.DAY_OF_MONTH, -1);
        }
        // System.out.println("要计算日期为:" + sdf.format(cal.getTime())); // 输出要计算日期
        // 设置一个星期的第一天，按中国的习惯一个星期的第一天是星期一
        cal.setFirstDayOfWeek(Calendar.MONDAY);
        // 获得当前日期是一个星期的第几天
        int day = cal.get(Calendar.DAY_OF_WEEK);
        // 根据日历的规则，给当前日期减去星期几与一个星期第一天的差值
        cal.add(Calendar.DATE, cal.getFirstDayOfWeek() - day);

        Date sTime = cal.getTime();
        cal.add(Calendar.DATE, 6);
        Date eTime = cal.getTime();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        TimeRange timeRange = null;
        try {
            timeRange = new TimeRange(sdf.parse(sdf.format(sTime)), sdf.parse(sdf.format(eTime)));
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return timeRange;
    }


    /**
     * 根据当前日期获得上周的日期区间（上周周一和周日日期）
     *
     * @return
     */
    public static TimeRange getLastWeekRange(Date date) {
        Calendar calendar1 = Calendar.getInstance();
        Calendar calendar2 = Calendar.getInstance();

        calendar1.setTime(date);
        calendar2.setTime(date);
        int dayOfWeek = calendar1.get(Calendar.DAY_OF_WEEK) - 1;
        int offset1 = 1 - dayOfWeek;
        int offset2 = 7 - dayOfWeek;
        calendar1.add(Calendar.DATE, offset1 - 7);
        calendar2.add(Calendar.DATE, offset2 - 7);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        TimeRange timeRange = null;
        try {
            timeRange = new TimeRange(sdf.parse(sdf.format(calendar1.getTime())), sdf.parse(sdf.format(calendar2.getTime())));
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return timeRange;
    }

    public static void main(String[] args) {
        TimeRange time1 =  getThisWeekRange(new Date());
        TimeRange time2 =  getLastWeekRange(new Date());

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        System.out.println(sdf.format(time1.getsTime()) +  "- " + sdf.format(time1.geteTime()));
        System.out.println(sdf.format(time2.getsTime()) + "- " +  sdf.format(time2.geteTime()));
    }

    //获得本周一0点时间
    public static Date getTimesWeekmorning() {
        Calendar cal = Calendar.getInstance();
        cal.setFirstDayOfWeek(Calendar.MONDAY);
        cal.set(cal.get(Calendar.YEAR), cal.get(Calendar.MONDAY), cal.get(Calendar.DAY_OF_MONTH), 0, 0, 0);
        cal.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
        return  cal.getTime();
    }
    //获得本周日24点时间
    public static Date getTimesWeeknight() {
        Calendar cal = Calendar.getInstance();
        cal.setTime(getTimesWeekmorning());
        cal.add(Calendar.DAY_OF_WEEK, 7);
        return cal.getTime();
    }

    /**
     * 获取当年的第一天
     * @param year
     * @return
     */
    public static Date getCurrYearFirst(){
        Calendar currCal=Calendar.getInstance();
        int currentYear = currCal.get(Calendar.YEAR);
        return getYearFirst(currentYear);
    }

    /**
     * 获取当年的最后一天
     * @param year
     * @return
     */
    public static Date getCurrYearLast(){
        Calendar currCal=Calendar.getInstance();
        int currentYear = currCal.get(Calendar.YEAR);
        return getYearLast(currentYear);
    }

    /**
     * 获取某年第一天日期
     * @param year 年份
     * @return Date
     */
    public static Date getYearFirst(int year){
        Calendar calendar = Calendar.getInstance();
        calendar.clear();
        calendar.set(Calendar.YEAR, year);
        Date currYearFirst = calendar.getTime();
        return currYearFirst;
    }

    /**
     * 获取某年最后一天日期
     * @param year 年份
     * @return Date
     */
    public static Date getYearLast(int year){
        Calendar calendar = Calendar.getInstance();
        calendar.clear();
        calendar.set(Calendar.YEAR, year);
        calendar.roll(Calendar.DAY_OF_YEAR, -1);
        Date currYearLast = calendar.getTime();

        return currYearLast;
    }
}
